package com.lxl.bt.util;

import android.media.MediaRecorder;
import android.os.Handler;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * @Author : xinlong.lv
 */
public class MediaRecordUtils {

    private static final String TAG = MediaRecordUtils.class.getSimpleName();

    private MediaRecorder mMediaRecorder;
    // 最大录音时长，单位毫秒，1000*60*60;
    private int maxLength = 1000 * 60 * 5;

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());

    //    //录音文件根目录
//    private String fileFolder;

    //文件路径
    private String filePath;

    private long startTime;
    private long endTime;

    private OnAudioStatusUpdateListener audioStatusUpdateListener;

    //倒计时秒数
    private int second;

    private final int BASE = 1;
    // 间隔取样时间
    private final int SPACE = 1000;

    /**
     * 是否是倒计时显示录音时长
     */
    private boolean isCountdown = true;

    /**
     * 文件存储默认sdcard/record
     */
    public MediaRecordUtils() {

//        fileFolder = Environment.getExternalStorageDirectory().getPath() + "/AudioRecord";
//        File path = new File(fileFolder);
//        if (!path.exists()) {
//            path.mkdirs();
//        }

//        File path = new File(filePath);
//        if (!path.exists())
//            path.mkdirs();

    }

    public String getFilePath() {
        return filePath;
    }

    public void setMaxLength(int maxLength) {
        this.maxLength = maxLength;
    }

    public int getMaxLength() {
        return maxLength;
    }

    public boolean isCountdown() {
        return isCountdown;
    }

    public void setCountdown(boolean countdown) {
        isCountdown = countdown;
    }

    /**
     * 开始录音 使用aac格式
     *
     * @param rootFileFolder 录音文件存放的根目录
     */
    public void startRecord(String rootFileFolder) {

        filePath = rootFileFolder + "/" + sdf.format(new Date()) + ".mp3";

        Log.e(TAG, "startRecord: filePath======" + filePath);

        // 开始录音
        /* ①Initial：实例化MediaRecorder对象 */
        if (mMediaRecorder == null) {
            mMediaRecorder = new MediaRecorder();
        }
        try {
            /* ②setAudioSource/setVideoSource */
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);// 设置麦克风
            /* ②设置音频文件的编码：AAC/AMR_NB/AMR_MB/Default 声音的（波形）的采样 */
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            /*
             * ②设置输出文件的格式：THREE_GPP/MPEG-4/RAW_AMR/Default THREE_GPP(3gp格式
             * ，H263视频/ARM音频编码)、MPEG-4、RAW_AMR(只支持音频且音频编码要求为AMR_NB)
             */
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
            /* ③准备 */
            mMediaRecorder.setOutputFile(filePath);
            mMediaRecorder.setMaxDuration(maxLength);
            mMediaRecorder.prepare();

            second = isCountdown ? maxLength : 0;

            /* ④开始 */
            mMediaRecorder.start();
            // AudioRecord audioRecord.
            /* 获取开始时间* */

            startTime = System.currentTimeMillis();
            updateMicStatus();
            Log.d(TAG, "startTime======" + startTime);
        } catch (IOException e) {
            Log.e(TAG, "e======" + e.getMessage());
        }
    }

    /**
     * 停止录音
     *
     * @param isClickStop true: 主动点击停止； false：最大时长倒计时结束
     * @return 录音时长
     */
    public long stopRecord(boolean isClickStop) {
        if (mMediaRecorder == null) {
            return 0L;
        }
        endTime = System.currentTimeMillis();

        //有一些网友反应在5.0以上在调用stop的时候会报错，翻阅了一下谷歌文档发现上面确实写的有可能会报错的情况，
        // 捕获异常清理一下就行了，感谢大家反馈！
        try {
            mMediaRecorder.stop();
            mMediaRecorder.reset();
            mMediaRecorder.release();
            mMediaRecorder = null;

            audioStatusUpdateListener.onStop(filePath, isClickStop);
            filePath = "";

        } catch (RuntimeException e) {
            try {
                mMediaRecorder.reset();
                mMediaRecorder.release();
                mMediaRecorder = null;

                File file = new File(filePath);
                if (file.exists()) {
                    file.delete();
                }

                filePath = "";

            } catch (Exception e1) {

            }

        }
        return endTime - startTime;
    }

    /**
     * 取消录音
     */
    public void cancelRecord() {
        try {
            mMediaRecorder.stop();
            mMediaRecorder.reset();
            mMediaRecorder.release();
            mMediaRecorder = null;
        } catch (RuntimeException e) {
            mMediaRecorder.reset();
            mMediaRecorder.release();
            mMediaRecorder = null;
        }
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        }
        filePath = "";
//        mHandler.removeCallbacks(mUpdateMicStatusTimer);
    }

    private final Handler mHandler = new Handler();
    private Runnable mUpdateMicStatusTimer = new Runnable() {
        @Override
        public void run() {
            if (isCountdown) {
                second = second - 1000;
                if (second >= 0) {
                    updateMicStatus();
                } else {
                    stopRecord(false);
                }
            } else {
                second = second + 1000;
                updateMicStatus();
            }
        }
    };


    /**
     * 更新麦克状态
     */
    private void updateMicStatus() {
        if (mMediaRecorder != null) {
            double ratio = (double) mMediaRecorder.getMaxAmplitude() / BASE;
            // 分贝
            double db = 0;
            if (ratio > 1) {
                db = 20 * Math.log10(ratio);
                if (null != audioStatusUpdateListener) {
                    audioStatusUpdateListener.onUpdate(db, second);
                }
            }
            mHandler.postDelayed(mUpdateMicStatusTimer, SPACE);
        }
    }


    public void setOnAudioStatusUpdateListener(OnAudioStatusUpdateListener audioStatusUpdateListener) {
        this.audioStatusUpdateListener = audioStatusUpdateListener;
    }

    public interface OnAudioStatusUpdateListener {

        /**
         * 录音中...
         *
         * @param db   当前声音分贝
         * @param time 录音时长
         */
        void onUpdate(double db, int time);

        /**
         * 停止录音
         *
         * @param filePath    文件保存路径
         * @param isClickStop 是否是主动点击的结束录音
         */
        void onStop(String filePath, boolean isClickStop);
    }

}
